package com.mida.dms.knw.service.impl;


import com.mida.dms.knw.entity.DtOid;
import com.mida.dms.knw.entity.DtUseSpace;
import com.mida.dms.knw.entity.DtUseSpaceConsumer;
import com.mida.dms.knw.entity.DtUseSpaceUnit;
import com.mida.dms.knw.entity.vo.DtUseSpaceConsumerVo;
import com.mida.dms.knw.entity.vo.DtUseSpacePage;
import com.mida.dms.knw.entity.vo.DtUseSpaceUnitVo;
import com.mida.dms.knw.entity.vo.DtUseSpaceVo;
import com.mida.dms.knw.mapper.*;
import com.mida.dms.knw.service.DtUseSpaceService;
import com.mida.dms.knw.service.SoidService;
import com.mida.dms.knw.util.CharTransFormUtil;
import com.mida.dms.knw.util.DataSetConstants;
import com.mida.dms.knw.vo.DtUseSpacePageVo;
import com.mida.dms.knw.vo.Page;
import com.mida.dms.knw.vo.PageResultVo;

import com.mida.tool.common.result.ActionResult;
import com.mida.tool.common.result.ListResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import static com.mida.dms.knw.Result.BaseResult.*;

/**
 * @author ：wang xiao le
 * @description：TODO
 * @date ：2021/3/23 17:30
 */
@Service
@Slf4j
@Transactional(value = "dtdTxManager", rollbackFor = Exception.class)
public class DtUseSpaceServiceImpl implements DtUseSpaceService {


    @Autowired
    private DtUseSpaceMapper dtUseSpaceMapper;

    @Autowired
    private DtUseSpaceConsumerMapper dtUseSpaceConsumerMapper;

    @Autowired
    private DtUseSpaceUnitMapper dtUseSpaceUnitMapper;
    @Autowired
    private KnwNoumenonUserSpaceMapper knwNoumenonUserSpaceMapper;

    @Autowired
    private SoidService soidService;
//    /**
//     * ID生成器
//     */
//    @Autowired
//    private OIDGanerator oIDGanerator;
//    /**
//     * OID
//     */
//    @Autowired
//    private DtOidMapper dtOidMapper;



    /**
     * 1、添加授权空间
     *
     * @param dtUseSpaceVo
     * @return
     */
    @Override
    public ActionResult add(DtUseSpaceVo dtUseSpaceVo) {
        if (dtUseSpaceVo.getUseSpaceSoid() != null) {
            log.info(dtUseSpaceVo.toString() + "不是一个新增，转到update去");
            return update(dtUseSpaceVo);
        }
        log.info("开始添加定义空间" + dtUseSpaceVo.toString());
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();

        try {
            if (StringUtils.isEmpty(dtUseSpaceVo.getUseSpaceName())) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("授权空间名称不能为空");
                return ar;
            }
            Integer count = dtUseSpaceMapper.countUseSpaceName(dtUseSpaceVo.getUseSpaceName());
            if (count > 0) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("授权空间名称已存在");
                return ar;
            }
            DtUseSpace dtUseSpace = new DtUseSpace();
            BeanUtils.copyProperties(dtUseSpaceVo, dtUseSpace);
//            DtUseSpace dtUseSpace = dtUseSpaceVo.toEntity(DtUseSpace.class);
            dtUseSpace.setPyCode(CharTransFormUtil.toPinyinSimple(dtUseSpaceVo.getUseSpaceName()));
            dtUseSpace.setWbCode(CharTransFormUtil.toWubi(dtUseSpaceVo.getUseSpaceName()));
//            Long seq = oIDGanerator.getSOID();
            Long seq = soidService.getSoid();
            dtUseSpace.setUseSpaceSoid(seq);
            dtUseSpace.setCreateDate(new Date());
            dtUseSpace.setUpdateDate(new Date());
            dtUseSpace.setIsDelete(0L);
            dtUseSpaceMapper.insert(dtUseSpace);//添加授权空间基本数据
            soidService.insertOid(seq,1);
//            String oid = oIDGanerator.getOID(0);
//            DtOid dtOid = new DtOid();
//            dtOid.setOid(oid);
//            dtOid.setSoid(seq);
//            dtOidMapper.insert(dtOid);
            //添加授权空间业务单元数据和授权空间用户数据
            addAuthSpaceUnit(dtUseSpaceVo, dtUseSpace);
            addUseSpaceConsumer(dtUseSpaceVo, dtUseSpace);
            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("添加授权空间异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(ar, "添加授权空间失败");
        } finally {
            st.stop();
            log.info("本次新增耗时:" + st.getTime() + "ms");
        }
        return ar;
    }

    /**
     * 2、更新授权空间
     *
     * @param dtUseSpaceVo
     * @return
     */
    @Override
    public ActionResult update(DtUseSpaceVo dtUseSpaceVo) {

        log.info("开始更新授权空间" + dtUseSpaceVo.toString());
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            if (dtUseSpaceVo.getUseSpaceSoid() == null) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("授权空间soid不能为空");
                return ar;
            }
            if (StringUtils.isEmpty(dtUseSpaceVo.getUseSpaceName())) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("授权空间名称不能为空");
                return ar;
            }
            Integer count = dtUseSpaceMapper.countUseSpaceName(dtUseSpaceVo.getUseSpaceName());
            DtUseSpace dtUseSpace = dtUseSpaceMapper.selectByPrimaryKey(dtUseSpaceVo.getUseSpaceSoid());
            if (count > 0 && !dtUseSpaceVo.getUseSpaceName().equals(dtUseSpace.getUseSpaceName())) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("授权空间名称已存在");
                return ar;
            }
            boolean equals = dtUseSpace.equals(dtUseSpaceVo);
            System.out.println("equals = " + equals);
            //1、校验授权空间基本信息是否修改
            if (!StringUtils.isEmpty(dtUseSpaceVo) && !dtUseSpace.equals(dtUseSpaceVo)) {
                //1、1更新授权空间基本数据
                dtUseSpace.setUseSpaceName(dtUseSpaceVo.getUseSpaceName());
                dtUseSpace.setPyCode(CharTransFormUtil.toPinyinSimple(dtUseSpaceVo.getUseSpaceName()));
                dtUseSpace.setWbCode(CharTransFormUtil.toWubi(dtUseSpaceVo.getUseSpaceName()));
                dtUseSpace.setHospitalSoid(dtUseSpaceVo.getHospitalSoid());
                dtUseSpace.setExamServiceType(dtUseSpaceVo.getExamServiceType());
                dtUseSpace.setUpdateDate(new Date());
                dtUseSpaceMapper.updateByPrimaryKeySelective(dtUseSpace);//更新授权空间基本数据
            }
            //2、校验是否修改授权空间业务单元数据
            List<DtUseSpaceUnitVo> sourceUnit = dtUseSpaceUnitMapper.findUseSpaceSoid(dtUseSpaceVo.getUseSpaceSoid());
            List<DtUseSpaceUnitVo> targetUnit = dtUseSpaceVo.getDtUseSpaceUnitList();
            boolean b = targetUnit.equals(sourceUnit);
            System.out.println("b = " + b);
            if (!targetUnit.isEmpty()) {//目标单元不为空
                if (!sourceUnit.isEmpty()) {//源单元不为空
                    if (!sourceUnit.equals(targetUnit)) { //业务单元有修改
                        //1、先删除
                        dtUseSpaceUnitMapper.deleteByUseSpaceSoid(dtUseSpaceVo.getUseSpaceSoid());
                        //2、添加授权空间业务单元数据
                        addAuthSpaceUnit(dtUseSpaceVo, dtUseSpace);
                    }
                } else {//源单元为空，直接插入
                    addAuthSpaceUnit(dtUseSpaceVo, dtUseSpace);
                }
            } else {//传入的目标单元为空，删除源业务单元
                dtUseSpaceUnitMapper.deleteByUseSpaceSoid(dtUseSpaceVo.getUseSpaceSoid());
            }

            //3、校验是否修改授权空间用户数据
            List<DtUseSpaceConsumerVo> sourceConsumer = dtUseSpaceConsumerMapper.findUseSpaceSoid(dtUseSpaceVo.getUseSpaceSoid());
            List<DtUseSpaceConsumerVo> targetConsumer = dtUseSpaceVo.getDtUseSpaceConsumerList();
            boolean equals1 = sourceConsumer.equals(targetConsumer);
            if (!targetConsumer.isEmpty()) {//目标授权空间用户不为空
                if (!sourceConsumer.isEmpty()) {//源授权空间用户不为空
                    if (!sourceConsumer.equals(targetConsumer)) {
                        //1、先删除
                        dtUseSpaceConsumerMapper.deleteByUseSpaceSoid(dtUseSpaceVo.getUseSpaceSoid());
                        //2、添加授权空间授权空间用户数据
                        addUseSpaceConsumer(dtUseSpaceVo, dtUseSpace);
                    }
                } else {//源授权空间用户为空，直接插入
                    addUseSpaceConsumer(dtUseSpaceVo, dtUseSpace);
                }
            } else {//传入的目标授权空间用户为空，删除源授权空间用户
                dtUseSpaceConsumerMapper.deleteByUseSpaceSoid(dtUseSpaceVo.getUseSpaceSoid());
            }

            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("添加授权空间异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(ar, "添加授权空间失败");
        } finally {
            st.stop();
            log.info("本次新增耗时:" + st.getTime() + "ms");
        }
        return ar;
    }

    /**
     * 添加授权空间业务单元数据
     *
     * @param dtUseSpaceVo 目标授权空间
     * @param dtUseSpace   源授权空间
     */
    private void addAuthSpaceUnit(DtUseSpaceVo dtUseSpaceVo, DtUseSpace dtUseSpace) {
        //添加授权空间业务单元数据
        List<DtUseSpaceUnitVo> dtUseSpaceUnitList = dtUseSpaceVo.getDtUseSpaceUnitList();
        if (dtUseSpaceUnitList.size() != 0) {
            for (DtUseSpaceUnit dtUseSpaceUnit : dtUseSpaceUnitList) {
//                dtUseSpaceUnit.setUseSpaceUnitSoid(oIDGanerator.getSOID());
                dtUseSpaceUnit.setUseSpaceUnitSoid(soidService.getSoid());
                dtUseSpaceUnit.setUseSpaceSoid(dtUseSpace.getUseSpaceSoid());
                dtUseSpaceUnit.setCreateDate(new Date());
                dtUseSpaceUnit.setUpdateDate(new Date());
                dtUseSpaceUnit.setIsDelete(0L);
                dtUseSpaceUnit.setStatus(dtUseSpace.getStatus());
                dtUseSpaceUnitMapper.insert(dtUseSpaceUnit);
            }
        }
    }
    /**
     * 添加授权空间用户数据
     *
     * @param dtUseSpaceVo 目标授权空间
     * @param dtUseSpace   源授权空间
     */
    private void addUseSpaceConsumer(DtUseSpaceVo dtUseSpaceVo, DtUseSpace dtUseSpace) {

        //添加授权空间用户数据
        List<DtUseSpaceConsumerVo> dtUseSpaceConsumerList = dtUseSpaceVo.getDtUseSpaceConsumerList();
        DtUseSpaceConsumer dtUseSpaceConsumer = new DtUseSpaceConsumer();
        if (dtUseSpaceConsumerList.size() != 0) {
            for (DtUseSpaceConsumerVo dtUseSpaceConsumerVo : dtUseSpaceConsumerList) {
//                dtUseSpaceConsumer.setSpaceConsumerSoid(oIDGanerator.getSOID());
                dtUseSpaceConsumerVo.setSpaceConsumerSoid(soidService.getSoid());
                dtUseSpaceConsumerVo.setUseSpaceSoid(dtUseSpace.getUseSpaceSoid());
                dtUseSpaceConsumerVo.setCreateDate(new Date());
                dtUseSpaceConsumerVo.setUpdateDate(new Date());
                dtUseSpaceConsumerVo.setStatus(dtUseSpace.getStatus());
                dtUseSpaceConsumerVo.setIsDelete(0L);
                BeanUtils.copyProperties(dtUseSpaceConsumerVo, dtUseSpaceConsumer);
                dtUseSpaceConsumerMapper.insert(dtUseSpaceConsumer);
            }
        }
    }


    @Override
    @Transactional(value = "dtdTxManager", rollbackFor = Exception.class)
    public ActionResult delete(long useSpaceSoid) {
        log.info("开始删除一个授权空间: " + useSpaceSoid);
        StopWatch stopWatch = StopWatch.createStarted();
        ActionResult actionResult = new ActionResult();
        try {
            DtUseSpaceVo dtUseSpaceVo = dtUseSpaceMapper.selectByUseSpaceSoid(useSpaceSoid);
            if (dtUseSpaceVo.getStatus().longValue() == 149L) {
                buildBadRequestActionWarn(actionResult, "授权空间已启用,无法删除");
                return actionResult;
            }
            Integer count = knwNoumenonUserSpaceMapper.countUseSpace(useSpaceSoid);
            if (count > 0) {
                buildBadRequestActionWarn(actionResult, "授权空间正在被使用,无法删除");
                return actionResult;
            }
            //删除授权空间
            dtUseSpaceMapper.deleteByPrimaryKey(useSpaceSoid);
            //删除授权空间用户
            dtUseSpaceConsumerMapper.deleteByUseSpaceSoid(useSpaceSoid);
            buildActionSuccess(actionResult);
        } catch (Exception e) {
            log.error("删除授权空间发送异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(actionResult, "删除授权空间失败");
        } finally {
            stopWatch.stop();
            log.info("本次删除耗时: " + stopWatch.getTime() + "ms");
        }
        return actionResult;
    }

    /**
     * 4、获取单个授权空间
     *
     * @param useSpaceSoid 授权空间soid
     * @return
     */
    @Override
    public ListResult<DtUseSpaceVo> get(long useSpaceSoid) {
        log.info("开始获取单个授权空间" + useSpaceSoid);
        StopWatch st = StopWatch.createStarted();
        ListResult<DtUseSpaceVo> lr = new ListResult<DtUseSpaceVo>();
        try {
            if (StringUtils.isEmpty(String.valueOf(useSpaceSoid))) {
                lr.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                lr.setMessage("授权空间soid不能为空");
                return lr;
            }
            //获取定义空间
            DtUseSpaceVo dtUseSpaceVo = dtUseSpaceMapper.selectByUseSpaceSoid(useSpaceSoid);
            buildListSuccess(lr, dtUseSpaceVo);
        } catch (Exception e) {
            log.error("获取单个定义空间发送异常", e);
            buildListWarn(lr, "获取单个定义空间失败");
        } finally {
            st.stop();
            log.info("本次删除耗时:" + st.getTime() + "ms");
        }
        return lr;
    }

    @Override
    public ListResult<PageResultVo<DtUseSpaceVo>> findPage(DtUseSpacePageVo vo) {
        log.info("开始授权空间分页查询,查询条件: " + vo.toString());
        ListResult result = new ListResult();
        PageResultVo pageResultVo = new PageResultVo();
        Page page = new Page(vo.getCurrentPage(), vo.getPageSize());
        pageResultVo.setPage(page);
        StopWatch stopWatch = StopWatch.createStarted();

        List<DtUseSpaceVo> list = null;
        try {
            DtUseSpacePage npage = new DtUseSpacePage(vo.getCurrentPage(), vo.getPageSize(), vo.getSearchData().trim());
            Integer count = dtUseSpaceMapper.findPageCount(npage);
            if (count > 0) {
                page.setTotalCount(count);
                list = dtUseSpaceMapper.findPage(npage);
            }else {
                page.setTotalCount(count);
                list = new ArrayList<DtUseSpaceVo>(0);
            }
            pageResultVo.setList(list);
            buildListSuccess(result, pageResultVo);
        } catch (Exception e) {
            list = new ArrayList<DtUseSpaceVo>(0);
            pageResultVo.setList(list);
            log.error("分页查询授权空间发送异常");
            buildListWarn(result, "分页查询授权空间失败");
        } finally {
            stopWatch.stop();
            log.info("本体分页查询耗时: " + stopWatch.getTime() + "ms");
        }
        return result;
    }

    /**
     * 6、授权空间名称重复性校验
     */
    @Override
    public ActionResult checkName(String name, Long useSpaceSoid) {
        log.info("开始检查是否重名" + name);
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            if (StringUtils.isEmpty(name)) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("授权空间名称不能为空");
                return ar;
            }
            Integer count = dtUseSpaceMapper.countUseSpaceName(name);
            if (count > 0 && useSpaceSoid == null) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("授权空间名称已存在");
                return ar;
            }
            if (useSpaceSoid != null) {
                DtUseSpace dtUseSpace = dtUseSpaceMapper.selectByPrimaryKey(useSpaceSoid);
                if (count > 0 && !dtUseSpace.getUseSpaceName().equals(name)) {
                    ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                    ar.setMessage("授权空间名称已存在");
                    return ar;
                }
            }
            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("检查是否重名异常", e);
            buildActionWarn(ar, "检查是否重名异常");
        } finally {
            st.stop();
            log.info("本次检查耗时:" + st.getTime() + "ms");
        }
        return ar;
    }

    /**
     * 7、更改授权空间状态
     *
     * @param useSpaceSoid 授权空间soid
     * @param status       状态soid
     * @return
     */
    @Override
    public ActionResult updateStatus(Long status, Long useSpaceSoid) {
        log.info("开始更新授权空间状态" + status);
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            if (status == null) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("授权空间状态不能为空");
                return ar;
            }
            if (useSpaceSoid == null) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("授权空间soid不能为空");
                return ar;
            }
            Integer countUseSum = knwNoumenonUserSpaceMapper.countUseSpace(useSpaceSoid);
            if (countUseSum != 0 && DataSetConstants.CLOSESTATUS.equals(status)) {
                ar.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                ar.setMessage("授权空间已被引用，不能停用");
                return ar;
            }
            //1、更新授权空间状态
            DtUseSpace dtUseSpace = new DtUseSpace();
            dtUseSpace.setUseSpaceSoid(useSpaceSoid);
            dtUseSpace.setStatus(status);
            dtUseSpace.setUpdateDate(new Date());
            dtUseSpaceMapper.updateByPrimaryKeySelective(dtUseSpace);
            //2、更新关系表状态
            dtUseSpaceUnitMapper.updateStatusByUseSpaceSoid(status, useSpaceSoid);
            dtUseSpaceConsumerMapper.updateStatusByUseSpaceSoid(status, useSpaceSoid);
            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("更新授权空间状态异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(ar, "更新授权空间状态失败");
        } finally {
            st.stop();
            log.info("本次检查耗时:" + st.getTime() + "ms");
        }
        return ar;
    }

    /**
     * 8、授权空间下拉(查询所有授权空间)
     *
     * @return
     */
    @Override
    public ListResult<List<DtUseSpace>> findAll() {
        log.info("开始查询所有授权空间");
        ListResult result = new ListResult();
        StopWatch stopWatch = StopWatch.createStarted();
        List<DtUseSpace> list = null;
        try {
            list = dtUseSpaceMapper.findAll();
            buildListSuccess(result, list);
        } catch (Exception e) {
            log.error("查询所有授权空间异常", e);
            buildListWarn(result, "查询所有授权空间失败");
        } finally {
            stopWatch.stop();
            log.info("本次查询耗时:" + stopWatch.getTime() + "ms");
        }
        return result;
    }


}
